package com.zyp.common.message.common.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URL;
import java.util.List;

public class AccessInterceptor extends HandlerInterceptorAdapter {

    private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
    private List<String> defaultAccessAllowedFrom;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String referer = request.getHeader("Referer");
        if (null == referer) { // 本域
            response.setHeader("Access-Control-Allow-Origin", "*");
        } else {
            URL u = new URL(referer);
            String host = u.getHost().toLowerCase();
            int port = u.getPort();
            for (String s : getDefaultAccessAllowedFrom()) {
                if (host.matches(s)) {
                    String url = null;
                    if (referer.startsWith("http:")) {
                        url = "http://".concat(host);
                        if (port != -1) {
                            url = url.concat(":" + String.valueOf(port));
                        }
                        response.setHeader("Access-Control-Allow-Origin", url);
                    } else if (referer.startsWith("https:")) {
                        url = "https://".concat(host);
                        if (port != -1) {
                            url=url.concat(":" + String.valueOf(port));
                        }
                        response.setHeader("Access-Control-Allow-Origin", url);
                    }
                    LOGGER.error(url);
                    break;
                }
            }
        }
        response.setHeader("Access-Control-Allow-Origin", "*");
        return true;
    }

    public List<String> getDefaultAccessAllowedFrom() {
        return defaultAccessAllowedFrom;
    }

    public void setDefaultAccessAllowedFrom(List<String> defaultAccessAllowedFrom) {
        this.defaultAccessAllowedFrom = defaultAccessAllowedFrom;
    }
}
